#include "musiclist.h"



MusicList::MusicList()
{

}

void MusicList::addMusicByUrl(QList<QUrl>urls)
{

    for(auto musicUrl : urls)
    {
        // 由于添加进来的⽂件不⼀定是歌曲⽂件，因此需要再次筛选出⾳乐⽂件
        QMimeDatabase db;
        QMimeType mime = db.mimeTypeForFile(musicUrl.toLocalFile());
        // if(mime.name() != "audio/mpeg" && mime.name() != "audio/flac")
        // {
        //     continue;
        // }
        // 如果是⾳乐⽂件，加⼊歌曲列表
        qDebug()<<musicUrl;
        Music mu(musicUrl);
        musicList.push_back(mu);
    }

}

void MusicList::writeToDB()
{
    for(auto music : musicList)
     {
     // 让music对象将⾃⼰写⼊数据库
     music.insertMusicToDB();
    }
}

void MusicList::readFromDB()
{
    QString sql("SELECT musicId, musicName, musicSinger, albumName,\
     duration, musicUrl, isLike, isHistory \
     FROM musicInfo");
     QSqlQuery query;
     if(!query.exec(sql))
     {
     qDebug()<<"数据库查询失败";
     return;
     }
    while(query.next())
     {
     Music music;
     music.setMusicId(query.value(0).toString());
     music.setMusicName(query.value(1).toString());
     music.setMusicSinger(query.value(2).toString());
     music.setMusicAlbum(query.value(3).toString());
     music.setMusicDuration(query.value(4).toLongLong());
     music.setMusicUrl(query.value(5).toString());
     music.setIsLike(query.value(6).toBool());
     music.setIsHistory(query.value(7).toBool());
     musicList.push_back(music);
     }
}

MusicList::iterator MusicList::begin()
{
    return musicList.begin();
}

MusicList::iterator MusicList::end()
{
    return musicList.end();
}

MusicList::iterator MusicList::findMusicById(const QString &musicId)
{
    for(iterator it = begin(); it != end(); ++it)
    {
        if(it->getMusicId() == musicId)
        {
            return it;
        }
    }
    return end();
}
